package org.kailu.book.controller;

import org.kailu.book.entity.DepartmentEntity;
import org.kailu.book.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class DepartmentController {

	@Autowired 
	private DepartmentService departmentService;
	
	@RequestMapping("/department")
	public String getData(ModelMap map) {
		map.addAttribute("departmentList", departmentService.getAll());
		return "department";
	}
	
	@RequestMapping(value = "/department/saveorupdate", method = RequestMethod.GET)
	public String initData(ModelMap map) {
		map.addAttribute("department",new DepartmentEntity());
		return "department_new";
	}
	
	@RequestMapping(value = "/department/saveorupdate", method = RequestMethod.POST)
    public String add(@ModelAttribute(value="department") DepartmentEntity departmentEntity, BindingResult result, ModelMap map)
    {
		departmentService.save(departmentEntity);
		return "redirect:/department";
    }
	
	@RequestMapping(value = "/department/saveorupdate/{departmentId}", method = RequestMethod.GET)
    public String update(@PathVariable("departmentId") int departmentId, ModelMap map)
    {
		map.addAttribute("department", departmentService.get(departmentId));
		return "department_new";
    }
	
	@RequestMapping(value = "/department/delete/{departmentId}", method = RequestMethod.GET)
    public String delete(@PathVariable("departmentId") int departmentId)
    {
		this.departmentService.delete(departmentId);
		return "redirect:/department";
    }
	
}
